<template>
  <div class="forget-container">
    <div class="forget-box">
      <div class="forget-title">
        <h2>找回密码</h2>
        <p>通过手机号验证重置您的密码</p>
      </div>
      
      <el-steps :active="activeStep" finish-status="success" simple class="forget-steps">
        <el-step title="验证身份" />
        <el-step title="重置密码" />
        <el-step title="完成" />
      </el-steps>
      
      <!-- 步骤1：身份验证 -->
      <el-form 
        v-if="activeStep === 0" 
        ref="verifyFormRef" 
        :model="verifyForm" 
        :rules="verifyRules" 
        class="forget-form"
        label-position="top"
      >
        <el-form-item label="手机号码" prop="phone">
          <el-input 
            v-model="verifyForm.phone" 
            placeholder="请输入注册时的手机号" 
            prefix-icon="Phone"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="验证码" prop="verifyCode">
          <div class="verify-code-container">
            <el-input 
              v-model="verifyForm.verifyCode" 
              placeholder="请输入验证码"
              maxlength="6"
              clearable
            />
            <el-button 
              :disabled="countdown > 0"
              @click="sendVerifyCode"
            >
              {{ countdown > 0 ? `重新发送(${countdown}s)` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="forget-button" 
            @click="verifyIdentity"
          >
            下一步
          </el-button>
        </el-form-item>
        
        <div class="login-link">
          想起密码了? <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
      
      <!-- 步骤2：重置密码 -->
      <el-form 
        v-if="activeStep === 1" 
        ref="resetFormRef" 
        :model="resetForm" 
        :rules="resetRules" 
        class="forget-form"
        label-position="top"
      >
        <div class="reset-info">
          <p>请设置新密码</p>
        </div>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="resetForm.newPassword" 
            placeholder="请输入新密码（6-20个字符）" 
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="resetForm.confirmPassword" 
            placeholder="请再次输入新密码" 
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button @click="activeStep = 0" class="prev-button">上一步</el-button>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="reset-button" 
            @click="resetUserPassword"
          >
            重置密码
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 步骤3：完成 -->
      <div v-if="activeStep === 2" class="success-container">
        <div class="success-icon">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <h3>密码重置成功</h3>
        <p>您的密码已经重置成功，请使用新密码登录</p>
        <el-button type="primary" class="forget-button" @click="goToLogin">立即登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleCheck } from '@element-plus/icons-vue'
import { getVerifyCode, resetPassword } from '@/api/user'

const router = useRouter()
const verifyFormRef = ref(null)
const resetFormRef = ref(null)
const loading = ref(false)
const activeStep = ref(0)
const countdown = ref(0)

// 验证表单数据
const verifyForm = reactive({
  phone: '',
  verifyCode: ''
})

// 重置密码表单数据
const resetForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 自定义验证规则
const validatePassword = (rule, value, callback) => {
  if (value !== resetForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

// 表单验证规则
const verifyRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}

// 重置密码验证规则
const resetRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

// 发送验证码
const sendVerifyCode = () => {
  if (countdown.value > 0) return
  
  verifyFormRef.value.validateField('phone', (valid) => {
    if (!valid) {
      loading.value = true
      
      // 调用发送验证码API
      getVerifyCode(verifyForm.phone)
        .then(() => {
          ElMessage.success('验证码已发送，请注意查收')
          // 开始倒计时
          countdown.value = 60
          const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        })
        .catch(error => {
          ElMessage.error(error.message || '验证码发送失败，请稍后重试')
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 验证身份
const verifyIdentity = () => {
  verifyFormRef.value.validate(valid => {
    if (!valid) return
    
    loading.value = true
    
    // 模拟API调用验证手机和验证码
    setTimeout(() => {
      loading.value = false
      activeStep.value = 1
    }, 1000)
  })
}

// 重置密码
const resetUserPassword = () => {
  resetFormRef.value.validate(valid => {
    if (!valid) return
    
    loading.value = true
    
    // 调用重置密码API
    resetPassword({
      phone: verifyForm.phone,
      verifyCode: verifyForm.verifyCode,
      newPassword: resetForm.newPassword
    })
      .then(() => {
        // 重置成功，进入第三步
        activeStep.value = 2
      })
      .catch(error => {
        ElMessage.error(error.message || '密码重置失败，请稍后重试')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.forget-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/images/login-bg.jpg') no-repeat center center;
  background-size: cover;
  
  .forget-box {
    width: 450px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  }
  
  .forget-title {
    text-align: center;
    margin-bottom: 20px;
    
    h2 {
      font-size: 24px;
      color: #333;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 14px;
      color: #666;
      margin: 0;
    }
  }
  
  .forget-steps {
    margin-bottom: 30px;
  }
  
  .forget-form {
    .el-form-item {
      margin-bottom: 20px;
    }
    
    .el-input {
      height: 45px;
      
      :deep(.el-input__wrapper) {
        padding: 0 15px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        
        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }
    }
  }
  
  .verify-code-container {
    display: flex;
    
    .el-input {
      flex: 1;
      margin-right: 10px;
    }
    
    .el-button {
      width: 120px;
    }
  }
  
  .forget-button, .reset-button {
    width: 100%;
    height: 45px;
    border-radius: 4px;
    font-size: 16px;
  }
  
  .prev-button {
    width: 100px;
    height: 45px;
    margin-right: 10px;
  }
  
  .login-link {
    text-align: center;
    margin: 15px 0;
    font-size: 14px;
    color: #666;
  }
  
  .reset-info {
    text-align: center;
    margin-bottom: 20px;
    color: #666;
  }
  
  .success-container {
    text-align: center;
    padding: 30px 0;
    
    .success-icon {
      font-size: 60px;
      color: #67c23a;
      margin-bottom: 20px;
    }
    
    h3 {
      font-size: 24px;
      color: #333;
      margin-bottom: 15px;
    }
    
    p {
      font-size: 14px;
      color: #666;
      margin-bottom: 30px;
    }
  }
}

// 移动端适配
@media (max-width: 576px) {
  .forget-container {
    .forget-box {
      width: 90%;
      padding: 30px 20px;
    }
    
    .verify-code-container {
      .el-button {
        width: 100px;
        font-size: 12px;
      }
    }
  }
}
</style> 